/* eslint-disable camelcase */
import { QuestionCircleOutlined } from '@ant-design/icons';

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';

import { Popconfirm, message } from 'antd';
import { connect } from 'dva';
import React, { PureComponent } from 'react';

import styles from './index.less';
import TableItem from './tableItem';

import { DATA_ENTRY, AdvancedSearch, SecondHeaderC, PrimaryGhostC, PrimaryC, ModalC, InputC, IconC } from '../../comps';

@Form.create()
class SceneSettings extends PureComponent {
  state = {
    isEditTitle: '', // 情景名称编辑
    isEdit: false, // 表格编辑
    visible: false,
    tableList: [],
    tableListTemplate: [],
    sceneId: 1, // 系统默认
    isSystem: 1, // 是否为系统默认
    sceneName: '系统默认',
    scenesList: [], // 情景设置
    SCENARIO_CATEGORY_dataSource: [], // 情景假设类别
    CREDIT_DEFAULT_RATE_dataSource: [], // 信用债违约率
    BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND_dataSource: [], // 债券收益率曲线上移幅度（信用债）
    BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND_dataSource: [], // 债券收益率曲线上移幅度（利率债）
    OTHER_PARAMETER_SETTINGS_dataSource: [], // 其它参数设置
    BOND_YIELD_CURVE_UP_BP_dataSource: [], // 债券收益率曲线上移幅度
    NON_STANDARD_BUSINESS_SCENARIO_dataSource: [], // 非标业务情景
    OTHER_PARAM_CONFIG_dataSource: [], // 配置项
  };

  componentDidMount() {
    this.props.onRef && this.props.onRef(this);
    this.getScenesList();
    this.getSceneInfo();
  }

  componentWillUnmount() {}

  // 获取下拉数据源
  getScenesList = (e) => {
    this.props.dispatch({
      type: 'stressTestReportSettingsM/getScenes',
      payload: {},
      callback: (data) => {
        if (!(data != undefined && data.length > 0)) return;
        this.setState({
          scenesList: data, // 初始化下拉数据
        });
        if (e) {
          this.sceneSearch.props.form.setFieldsValue({
            sceneId: e,
          });
          const temp = data.filter((item) => item.value === e);
          this.setState({
            sceneId: e,
            sceneName: temp[0].display,
            isSystem: temp[0].isSystem,
          });
        } else {
          this.sceneSearch.props.form.setFieldsValue({
            sceneId: data[0].value,
          });
          this.setState({
            sceneId: data[0].value,
            sceneName: data[0].display,
            isSystem: data[0].isSystem,
          });
        }
        // 更新localStorage记录
        // sessionStorage.setItem('scenesList', JSON.stringify(data));
      },
    });
  };

  // 获取情景设置信息
  getSceneInfo = () => {
    const { sceneId, tableListTemplate } = this.state;
    const SCENARIO_CATEGORY = [];
    const CREDIT_DEFAULT_RATE = [];
    const BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND = [];
    const BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND = [];
    const OTHER_PARAMETER_SETTINGS = [];
    const BOND_YIELD_CURVE_UP_BP = [];
    const NON_STANDARD_BUSINESS_SCENARIO = [];
    const OTHER_PARAM_CONFIG = [];
    this.props.dispatch({
      type: 'stressTestReportSettingsM/stressTestConfig',
      payload: {
        sceneId,
      },
      callback: (data) => {
        if (data && data.length > 0) {
          data.forEach((e) => {
            if (e.stressTestConfigGroup === 'SCENARIO_CATEGORY') {
              SCENARIO_CATEGORY.push(e);
            }
            if (e.stressTestConfigGroup === 'CREDIT_DEFAULT_RATE') {
              CREDIT_DEFAULT_RATE.push(e);
            }
            if (e.stressTestConfigGroup === 'BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND') {
              BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND.push(e);
            }
            if (e.stressTestConfigGroup === 'BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND') {
              BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND.push(e);
            }
            if (e.stressTestConfigGroup === 'OTHER_PARAMETER_SETTINGS') {
              OTHER_PARAMETER_SETTINGS.push(e);
            }
            if (e.stressTestConfigGroup === 'BOND_YIELD_CURVE_UP_BP') {
              BOND_YIELD_CURVE_UP_BP.push(e);
            }
            if (e.stressTestConfigGroup === 'NON_STANDARD_BUSINESS_SCENARIO') {
              NON_STANDARD_BUSINESS_SCENARIO.push(e);
            }
            if (e.stressTestConfigGroup === 'OTHER_PARAM_CONFIG') {
              OTHER_PARAM_CONFIG.push(e);
            }
          });
          this.setState({
            isEdit: false,
            tableList: data,
            tableListTemplate: tableListTemplate.length ? tableListTemplate : data,
            SCENARIO_CATEGORY_dataSource: SCENARIO_CATEGORY,
            CREDIT_DEFAULT_RATE_dataSource: CREDIT_DEFAULT_RATE, // 信用债违约率
            BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND_dataSource: BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND, // 债券收益率曲线上移幅度（信用债）
            BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND_dataSource: BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND, // 债券收益率曲线上移幅度（利率债）
            OTHER_PARAMETER_SETTINGS_dataSource: OTHER_PARAMETER_SETTINGS, // 其它参数设置
            BOND_YIELD_CURVE_UP_BP_dataSource: BOND_YIELD_CURVE_UP_BP, // 债券收益率曲线上移幅度
            NON_STANDARD_BUSINESS_SCENARIO_dataSource: NON_STANDARD_BUSINESS_SCENARIO, // 非标业务情景
            OTHER_PARAM_CONFIG_dataSource: OTHER_PARAM_CONFIG, // 股票单日可变现金额占平均市场成交金额的比例
          });
        }
      },
    });
  };

  // 查询条件
  renderForm = () => {
    const { scenesList } = this.state;
    const searchProps = {
      dataSource: [
        {
          dataIndex: 'sceneId',
          title: '情景名称',
          type: DATA_ENTRY.SELECT,
          allowClear: false,
          dataSource: scenesList.map((item) => {
            const obj = {
              title: item.display,
              value: item.value,
            };
            return obj;
          }),
          filterOption: (input, option) => option.props.children.indexOf(input) > -1,
          onChange: (e) => {
            const temp = scenesList.filter((item) => item.value === e);
            this.setState(
              {
                sceneId: e,
                sceneName: temp[0].display,
                isEdit: false,
                isSystem: temp[0].isSystem,
              },
              () => {
                this.getSceneInfo();
              },
            );
          },
        },
      ],
      selfButt: (
        <div className='scene-btn'>
          <IconC isHover={false} type='plus' title='新增' onClick={() => this.addScene()} />
          <IconC isHover={false} type='edit' title='编辑' onClick={() => this.editScene()} />
          <Popconfirm
            title='确定删除？'
            icon={<QuestionCircleOutlined />}
            onConfirm={() => {
              this.deleteScene();
            }}
          >
            <IconC isHover={false} type='deleteBlue' title='删除' />
          </Popconfirm>
        </div>
      ),
      allowClear: false,
      allowQuery: false,
      onRef: (ref) => {
        this.sceneSearch = ref;
      },
    };

    return (
      <div>
        <AdvancedSearch {...searchProps} />
      </div>
    );
  };

  // 新增情景名称
  addScene = () => {
    this.setState(
      {
        visible: true,
        isEditTitle: false,
      },
      () => {
        if (this.state.sceneNameRef) {
          this.state.sceneNameRef.props.form.setFieldsValue({
            sceneName: '',
          });
        }
      },
    );
  };

  // 编辑情景名称
  editScene = () => {
    if (this.state.isSystem == 1) {
      message.error('系统默认名称无法修改');
    } else {
      this.setState(
        {
          visible: true,
          isEditTitle: true,
        },
        () => {
          if (this.state.sceneNameRef) {
            this.state.sceneNameRef.props.form.setFieldsValue({
              sceneName: this.state.sceneName,
            });
          }
        },
      );
    }
  };

  // 情景名称保存
  addInfo = () => {
    const name = this.state.sceneNameRef.props.form.getFieldsValue().sceneName;
    if (this.state.isEditTitle && this.state.sceneName == name) {
      this.setState({
        visible: false,
        isEditTitle: false,
      });
      message.success('保存成功！');
    } else {
      this.props.dispatch({
        type: 'stressTestReportSettingsM/checkSceneName',
        payload: {
          name,
        },
        callback: (data) => {
          this.setState({
            visible: false,
          });
          if (data) {
            if (this.state.isEditTitle) {
              this.props.dispatch({
                type: 'stressTestReportSettingsM/sceneSettingsEditSceneName',
                payload: {
                  name, // 模板名称
                  id: this.state.sceneId,
                },
                callback: () => {
                  message.success('编辑成功！');
                  this.getScenesList(this.state.sceneId);
                  this.setState({
                    isEditTitle: false,
                  });
                },
              });
            } else {
              this.props.dispatch({
                type: 'stressTestReportSettingsM/sceneSettingsSave',
                payload: {
                  content: this.state.tableListTemplate,
                  name,
                },
                callback: () => {
                  message.success('添加成功！');
                  this.props.dispatch({
                    type: 'stressTestReportSettingsM/getScenes',
                    payload: {},
                    // eslint-disable-next-line no-shadow
                    callback: (data) => {
                      if (!(data != undefined && data.length > 0)) return;
                      this.setState({
                        scenesList: data, // 初始化下拉数据
                      });
                      const temp = data.filter((item) => item.display === name);
                      this.sceneSearch.props.form.setFieldsValue({
                        sceneId: temp[0].value,
                      });
                      this.setState(
                        {
                          sceneId: temp[0].value,
                          sceneName: temp[0].display,
                          isSystem: temp[0].isSystem,
                        },
                        () => {
                          this.getSceneInfo();
                        },
                      );
                    },
                  });
                },
              });
            }
          }
        },
      });
    }
  };

  deleteScene = () => {
    if (this.state.isSystem == 1) {
      message.error('系统默认名称无法删除');
    } else {
      this.props.dispatch({
        type: `stressTestReportSettingsM/judgeUsageStatus`,
        payload: {
          sceneId: this.state.sceneId,
        },
        callback: (data) => {
          // true-使用中  false-未使用
          if (!data.dataSource.inUse) {
            this.setState({
              isEdit: false,
            });
            this.props.dispatch({
              type: `stressTestReportSettingsM/sceneSettingsDelete`,
              payload: {
                id: this.state.sceneId,
              },
              // eslint-disable-next-line no-shadow
              callback: (data) => {
                if (data.code === 0 && data.data) {
                  message.success('删除成功！');
                  this.getScenesList();
                }
              },
            });
          } else {
            message.error('当前情景名称已有租户使用，无法删除');
          }
        },
      });
    }
  };

  // 编辑表格
  editBtn = () => {
    this.setState({
      isEdit: true,
    });
  };

  // 保存
  saveBtn = () => {
    const {
      tableList,
      SCENARIO_CATEGORY,
      CREDIT_DEFAULT_RATE,
      BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND,
      BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND,
      BOND_YIELD_CURVE_UP_BP,
      OTHER_PARAM_CONFIG,
    } = this.state;
    const obj = {
      ...SCENARIO_CATEGORY.getData(),
      ...CREDIT_DEFAULT_RATE.getData(),
      ...BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND.getData(),
      ...BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND.getData(),
      ...BOND_YIELD_CURVE_UP_BP.getData(),
      ...OTHER_PARAM_CONFIG.getData(),
    };
    const arr = [...tableList];
    arr.map((item) => {
      item.low = obj[`${item.stressTestType}_${item.code}_low`] ?? item.low;
      item.medium = obj[`${item.stressTestType}_${item.code}_medium`] ?? item.medium;
      item.high = obj[`${item.stressTestType}_${item.code}_high`] ?? item.high;
    });
    this.props.dispatch({
      type: 'stressTestReportSettingsM/stressTestConfigSave',
      payload: arr,
      callback: (res) => {
        if (res) {
          this.getSceneInfo();
        }
      },
    });
  };

  // 取消
  exitBtn = () => {
    this.setState({
      isEdit: false,
    });
  };

  render() {
    const {
      sceneName,
      visible,
      isEdit,
      isEditTitle,
      SCENARIO_CATEGORY_dataSource,
      CREDIT_DEFAULT_RATE_dataSource, // 信用债违约率
      BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND_dataSource, // 债券收益率曲线上移幅度（信用债）
      BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND_dataSource, // 债券收益率曲线上移幅度（利率债）
      BOND_YIELD_CURVE_UP_BP_dataSource, // 债券收益率曲线上移幅度
      OTHER_PARAM_CONFIG_dataSource, // 其他参数设置 - 配置项
    } = this.state;
    const {
      stressTestReportSettingsM: {
        SCENARIO_CATEGORY_columns,
        CREDIT_DEFAULT_RATE_columns,
        BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND_colunms,
        BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND_colunms,
        BOND_YIELD_CURVE_UP_BP_colunms,
        OTHER_PARAM_CONFIG_colunms,
      },
    } = this.props;
    return (
      <div className={styles.sceneBox}>
        {this.renderForm()}
        <div style={{ marginTop: '12px' }}>
          {isEdit ? (
            <div>
              <PrimaryGhostC onClick={() => this.saveBtn()} title='保存' style={{ marginRight: '12px' }} />
              <PrimaryGhostC onClick={() => this.exitBtn()} title='取消' />
            </div>
          ) : (
            <PrimaryC onClick={() => this.editBtn()} title='编辑' />
          )}
        </div>
        <div style={{ marginTop: '12px' }}>
          <SecondHeaderC title='固定收益类、权益类、混合类产品压力测试情景' />
        </div>
        {/* 情景假设类别 */}
        <TableItem isEdit={isEdit} columns={SCENARIO_CATEGORY_columns} dataSource={SCENARIO_CATEGORY_dataSource} onRef={(ref) => this.setState({ SCENARIO_CATEGORY: ref })} />
        {/* 信用债违约率 */}
        <TableItem isEdit={isEdit} columns={CREDIT_DEFAULT_RATE_columns} dataSource={CREDIT_DEFAULT_RATE_dataSource} onRef={(ref) => this.setState({ CREDIT_DEFAULT_RATE: ref })} />
        {/* 债券收益率曲线上移幅度（信用债） */}
        <TableItem
          isEdit={isEdit}
          columns={BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND_colunms}
          dataSource={BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND_dataSource}
          onRef={(ref) => this.setState({ BOND_YIELD_CURVE_UPSIDE_CREDIT_BOND: ref })}
        />
        {/* 债券收益率曲线上移幅度（利率债） */}
        <TableItem
          isEdit={isEdit}
          columns={BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND_colunms}
          dataSource={BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND_dataSource}
          onRef={(ref) => this.setState({ BOND_YIELD_CURVE_UPSIDE_INTEREST_RATE_BOND: ref })}
        />
        {/* 其它参数设置 */}
        {/* <TableItem /> */}
        {/* 现金管理类产品测试情景 */}
        <div style={{ marginTop: 20 }}>
          <SecondHeaderC title='现金管理类产品测试情景' />
        </div>
        <TableItem
          isEdit={isEdit}
          columns={BOND_YIELD_CURVE_UP_BP_colunms}
          dataSource={BOND_YIELD_CURVE_UP_BP_dataSource}
          onRef={(ref) => this.setState({ BOND_YIELD_CURVE_UP_BP: ref })}
        />
        <div style={{ marginTop: 20 }}>
          <SecondHeaderC title='其他参数配置' />
        </div>
        {/*配置项*/}
        <TableItem isEdit={isEdit} columns={OTHER_PARAM_CONFIG_colunms} dataSource={OTHER_PARAM_CONFIG_dataSource} onRef={(ref) => this.setState({ OTHER_PARAM_CONFIG: ref })} />
        {/* 非标业务情景 */}
        {/* <TableItem/> */}
        <ModalC
          visible={visible}
          onOk={this.addInfo}
          onCancel={() => {
            this.setState({
              visible: !visible,
              isEditTitle: false,
            });
          }}
          title={isEditTitle ? '编辑' : '新增'}
          width={420}
          okText='确认'
        >
          <Form>
            <InputC
              title='情景名称'
              dataIndex='sceneName'
              placeholder='请输入'
              initialValue={isEditTitle ? sceneName : ''}
              form={this.props.form}
              rules={[{ required: true, message: `请输入名称` }]}
              onRef={(ref) => this.setState({ sceneNameRef: ref })}
            />
          </Form>
        </ModalC>
      </div>
    );
  }
}
export default connect(({ stressTestReportSettingsM, loading }) => ({ stressTestReportSettingsM, loading }))(SceneSettings);
